﻿using System.Web.Mvc;
using System;
using System.Reflection;
using System.Linq;
using Microsoft.Practices.Unity;
using System.Web.Routing;

using iHouse.Model.Repository;
using iHouse.Model.Repository.Interface;
using iHouse.Common.Membership;
using iHouse.Model.Cache;

namespace iHouse.Web.Infrastructure
{
    public class UnityControllerFactory : DefaultControllerFactory
    {
        IUnityContainer _container;

        public UnityControllerFactory(IUnityContainer container)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }
            this._container = container;

            // Also register all the controller types as transient
            var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
                                  where typeof(IController).IsAssignableFrom(t)
                                  select t;

            foreach (Type t in controllerTypes)
            {
                this._container.RegisterType(typeof(IController), t, t.FullName);
            }

            this._container.RegisterType<IDataContextProvider, DataContextProvider>();
            this._container.RegisterType<IBookRepository, SqlBookRepository>();
            this._container.RegisterType<ICategoryRepository, SqlCategoryRepository>();
            this._container.RegisterType<IAlbumRepository, SqlAlbumRepository>();
            this._container.RegisterType<IPublisherRepository, SqlPublisherRepository>();
            this._container.RegisterType<IFormsAuthenticationService, FormsAuthenticationService>();
            this._container.RegisterType<IMembershipService, MembershipService>();
            this._container.RegisterType<INoteRepository, SqlNoteRepository>();
        }

        protected override IController GetControllerInstance(RequestContext context, System.Type controllerType)
        {
            return (IController)this._container.Resolve(controllerType);
        }
    }
}